<template>
    <div class="pb_a">
        <!--头部导航-->
        <van-nav-bar class="head_nb" :title="paper.title" left-text="返回" left-arrow @click-left="$router.back();">
            <van-count-down :time="totalTime" slot="right"/>
        </van-nav-bar>

        <!--标题说明-->
        <div class="pt_a ta_c">
            <div class="m_10 txt_cn">
                <div class="ft_14">{{paper.name}}</div>
                <div class="ft_10">考试时间：{{paper.timeRange | time-range}}（共{{paper.totalTime}}分钟）</div>
            </div>
        </div>

        <!--题目列表-->
        <div class="bg_w ft_14">
            <van-list
                v-model="loading"
                :finished="finished"
                finished-text="没有更多了"
                @load="onLoad">
                <div class="question p_10" v-for="item in questions" :key="item.id" :id="'question_'+item.sortNumber">
                    <h4 class="number">
                        第{{item.sortNumber}}题
                    </h4>

                    <!--综合知识-->
                    <div v-if="paper.questionType=='1'">
                        <div class="name">
                            {{item.name}}
                            <div class="question_image" v-if="item.fileUrl">
                                <van-image :src="item" v-for="item in item.fileUrl" :key="item" @click="showImage(item)"/>
                            </div>
                        </div>
                        <div class="option">
                            <div v-if="item.optionType=='1'">
                                <div class="option_item">
                                    A、{{item.choiceOption['A']}}
                                </div>
                                <div class="option_item">
                                    B、{{item.choiceOption['B']}}
                                </div>
                                <div class="option_item">
                                    C、{{item.choiceOption['C']}}
                                </div>
                                <div class="option_item">
                                    D、{{item.choiceOption['D']}}
                                </div>
                            </div>
                            <div v-if="item.optionType=='2'">
                                <div class="option_item">
                                    A、
                                    <van-image :src="item.choiceOption['A']" @click="showImage(item.choiceOption['A'])"/>
                                </div>
                                <div class="option_item">
                                    B、
                                    <van-image :src="item.choiceOption['B']" @click="showImage(item.choiceOption['B'])"/>
                                </div>
                                <div class="option_item">
                                    C、
                                    <van-image :src="item.choiceOption['C']" @click="showImage(item.choiceOption['C'])"/>
                                </div>
                                <div class="option_item">
                                    D、
                                    <van-image :src="item.choiceOption['D']" @click="showImage(item.choiceOption['D'])"/>
                                </div>
                            </div>
                            <div v-if="item.optionType=='3'">
                                <div class="option_item">
                                    <van-image :src="item.choiceOption['option']" @click="showImage(item.choiceOption['option'])"/>
                                </div>
                            </div>
                        </div>
                        <div class="answer pt_10">
                            <van-row type="flex">
                                <van-col span="4">
                                    答案：
                                </van-col>
                                <van-col span="20">
                                    <van-radio-group v-model="answers[item.sortNumber]">
                                        <van-col span="6">
                                            <van-radio name="A">A</van-radio>
                                        </van-col>
                                        <van-col span="6">
                                            <van-radio name="B">B</van-radio>
                                        </van-col>
                                        <van-col span="6">
                                            <van-radio name="C">C</van-radio>
                                        </van-col>
                                        <van-col span="6">
                                            <van-radio name="D">D</van-radio>
                                        </van-col>
                                    </van-radio-group>
                                </van-col>
                            </van-row>
                        </div>
                    </div>

                    <!--案例分析-->
                    <div v-if="paper.questionType=='2'">
                        <div class="name" v-html="item.name" @click="imageChange($event)"></div>

                        <div class="answer">
                            <van-cell-group title="我的答案">
                                <textarea v-model="answers[item.sortNumber]" rows="10" placeholder="请输入答案" class="van-field__control" style="height:240px;text-indent:15px;"></textarea>
                            </van-cell-group>
                        </div>
                    </div>

                    <!--论文-->
                    <div v-if="paper.questionType=='3'">
                        <div class="name" v-html="item.name" @click="imageChange($event)"></div>
                    </div>
                </div>
            </van-list>
        </div>

        <!--提交按钮-->
        <van-tabbar route v-if="paper.questionType!='3'">
            <van-tabbar-item replace icon="notes-o" class="bg_y txt_cw" @click="answerShow=true">答题卡</van-tabbar-item>
            <van-tabbar-item replace icon="success" class="bg_b txt_cw" @click="answerSubmit">提交</van-tabbar-item>
        </van-tabbar>

        <!--图片预览-->
        <van-image-preview
            v-model="imageShow"
            :startPosition='position'
            :images="images">
        </van-image-preview>

        <!--答题卡-->
        <van-popup
            v-model="answerShow"
            :style="{height: paper.questionType=='1'? '45%':'10%',width:'80%', top:'40%'}" class="pb_10">
            <van-row type="flex" justify="space-around" v-for="item in answerCard" :key="item.index" class="pt_10">
                <van-col span="4.8" v-for="item in item" :key="item.id" @click="answerCardItem(item.sortNumber)">
                    <span class="box_item" :class="{'box_item--active': answers[item.sortNumber]}">
                        <span class="box_item_name">{{item.sortNumber}}</span>
                    </span>
                </van-col>
            </van-row>
        </van-popup>

        <!--回到顶部-->
        <ToTop/>
    </div>
</template>

<script>
    import Vue from 'vue';
    import {mapState} from 'vuex';
    import common from '../../common/common'
    import {CountDown, Image, ImagePreview, List, Popup, Radio, RadioGroup, Tabbar, TabbarItem} from 'vant';
    import {getPaper, getPaperQuestion} from '../../api/index';
    import ToTop from '../../components/ToTop/ToTop';

    Vue.use(Popup);
    Vue.use(CountDown);
    Vue.use(ImagePreview);
    Vue.use(Image);
    Vue.use(Tabbar).use(TabbarItem);
    Vue.use(List);
    Vue.use(RadioGroup);
    Vue.use(Radio);

    export default {
        name: "Paper",
        components: {
            ToTop
        },
        data() {
            return {
                paper: {},
                questions: [],
                answers: [],
                images: [],
                position: 0,
                imageShow: false,
                answerShow: false,
                answerCard: [],
                loading: false,
                finished: false,
                pageNumber: 1,
                pageSize: 10,
                id: this.$route.query.id,
                mode: this.$route.query.mode,
                totalTime: 60 * 1000
            }
        },
        async created() {
            //获取试卷详情信息
            if (this.id != '') {
                var params = {'paperId': this.id};
                const result = await getPaper(params);
                if (result.code === 0) {
                    this.paper = result.data || {};
                    const questionType = this.paper.questionType;
                    const totalTime = this.paper.totalTime || 0;
                    if (questionType == '1') {
                        this.paper.title = '软考网综合知识练习';
                    } else if (questionType == '2') {
                        this.paper.title = '软考网案例分析练习';
                    } else if (questionType == '3') {
                        this.paper.title = '软考网论文练习';
                    }
                    this.totalTime = this.totalTime * totalTime;
                }
            }

            //判断是否登录
            if (this.user.userId == '') {
                common.dialog('游客您好，游客帐号是为用户展示会员中心部分功能应用的，系统不会保存游客做题答案等数据！\n\n' +
                    '若需使用全部功能，请免费注册会员！', () => {
                    this.$router.push('/login');
                });
            }

        },
        methods: {
            //异步加载试题列表
            async onLoad() {
                const params = {paperId: this.id, pageSize: this.pageSize, pageNumber: this.pageNumber};
                const result = await getPaperQuestion(params);
                if (result.code === 0) {
                    ++this.pageNumber;
                    if (result.data.length > 0) {
                        for (let i = 0; i < result.data.length; i++) {
                            let question = result.data[i];
                            question.choiceOption = JSON.parse(question.choiceOption);
                            let fileUrl = question.fileUrl || '';
                            if (fileUrl != '') {
                                question.fileUrl = fileUrl.split(',');
                                let fileUrlArr = fileUrl.split(',');
                                fileUrlArr.map((url) => {
                                    this.images.push(url);
                                });
                            }
                            let optionType = question.optionType || '';
                            if (optionType != '') {
                                if (optionType == '2') {
                                    this.images.push(question.choiceOption['A']);
                                    this.images.push(question.choiceOption['B']);
                                    this.images.push(question.choiceOption['C']);
                                    this.images.push(question.choiceOption['D']);
                                } else if (optionType == '3') {
                                    this.images.push(question.choiceOption['option']);
                                }
                            }
                            this.questions.push(result.data[i]);
                        }
                    }
                    // 加载状态结束
                    this.loading = false;

                    // 数据全部加载完成
                    if (this.pageNumber > result.pages) {
                        this.finished = true;
                    }
                }
            },
            //图片预览展示
            showImage(url) {
                const images = this.images;
                for (let i = 0; i < images.length; i++) {
                    const image = images[i];
                    if (image == url) {
                        this.imageShow = true;
                        this.position = i;
                    }
                }
            },
            //图片预览展示
            imageChange(e) {
                if (e.target.nodeName == 'IMG') {
                    ImagePreview({images: [e.target.currentSrc]})
                } else {
                    return;
                }
            },
            //点击答题卡
            answerCardItem(sortNumber) {
                this.answerShow = false;
                let block = 'center';
                const questionType = this.paper.questionType || '1';
                if (questionType == '2') {
                    block = 'start'
                }
                var element = document.getElementById("question_" + sortNumber);
                element.scrollIntoView({block: block, behavior: "smooth"});
            },
            //提交答案
            answerSubmit() {
                let answerFinish = true;
                const finished = this.finished;
                const questions = this.questions;
                const answers = this.answers;
                for (let i = 1; i < answers.length; i++) {
                    answers[i] = answers[i] || '';
                    if (answers[i] == '') {
                        answerFinish = false;
                        break;
                    }
                }
                if (!answerFinish || !finished || questions.length != answers.length - 1) {
                    common.dialog('您还未完成所有题目，是否确认提交答案？', () => {
                        this.answerSave();
                    });
                } else {
                    this.answerSave();
                }
            },
            //保存答案
            async answerSave() {
                let answers = this.answers;
                let newAnswers = [];
                for (let i = 1; i < answers.length; i++) {
                    answers[i] = answers[i] || '';
                    newAnswers.push({'number': i, answer: answers[i]});
                }
                let params = {paperId: this.id, answers: JSON.stringify(newAnswers), userId: this.user.userId};
                console.log(params);
                if (this.user.userId == '') {
                    common.dialog('游客您好，游客帐号是为用户展示会员中心部分功能应用的，系统不会保存游客做题答案等数据！\n\n' +
                        '若需使用全部功能，请免费注册会员！', () => {
                        this.$router.push('/login');
                    });
                    return;
                }
            }
        },
        watch: {
            questions: function () {
                this.answerCard = [];
                let questions = this.questions;
                for (var i = 0; i < questions.length; i += 5) {
                    this.answerCard.push(questions.slice(i, i + 5));
                }
            }
        },
        computed: {
            ...mapState(['user'])
        }
    }
</script>

<style scoped>
    .van-count-down {
        line-height: inherit;
    }

    .number {
        margin: 0;
    }

    .question {
        position: relative;
    }

    .question::after {
        border-width: 1px 0 !important;
    }

    [class^=question]::after {
        position: absolute;
        box-sizing: border-box;
        content: ' ';
        pointer-events: none;
        right: 0;
        bottom: 0;
        left: 0;
        border-bottom: 1px solid #ebedf0;
        -webkit-transform: scaleY(.5);
        transform: scaleY(.5);
    }

    .option_item {
        padding: 2px 0;
    }

    .van-field__control {
        border: 1px solid #ebedf0;
    }

    .name >>> img {
        display: block;
        width: 100%;
        height: 100%;
    }
</style>
